package com.jt.blog.exception;

import com.jt.blog.common.model.ExceptionDto;
import com.jt.blog.common.util.DateKit;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author : 戴瑞
 * @Description : 404 异常处理
 * @create : 2018-03-25 17:56
 **/

@Controller
public class HttpErrorHandler implements ErrorController {

    private final static String ERROR_PATH = "/error";

    /**
     * Supports the HTML Error View
     *
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public String errorHtml(HttpServletRequest request, HttpServletResponse response) {
        return "error";
    }

    /**
     * Supports other formats like JSON, XML
     *
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public Object error(HttpServletRequest request) {
        String dateFormat = DateKit.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
        ExceptionDto dto = new ExceptionDto(HttpStatus.NOT_FOUND.value(), "Sorry !  Page Not Found", request.getRequestURI(), dateFormat);
        return dto;
    }

    /**
     * Returns the path of the error page.
     *
     * @return the error path
     */
    @Override
    public String getErrorPath() {
        return "error";
    }
}

